package com.recharge.shiro;

import com.recharge.common.result.ResultDO;
import com.recharge.domain.UserLoginDO;
import com.recharge.service.UserLoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 *
 */
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserLoginService userLoginService;

    /**
     * 权限相关
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        //账户
        String username = (String) SecurityUtils.getSubject().getPrincipal();
        ResultDO result = userLoginService.getUserByName(username);

        if(!result.isSuccess()) {
            throw new UnknownAccountException("登陆失败");
        }
        UserLoginDO domain = (UserLoginDO) result.getModel(ResultDO.FIRST_MODEL_KEY);

       return new SimpleAuthenticationInfo(
                domain.getId(),
                domain.getPassword(),
                ByteSource.Util.bytes(username),
                getName()
        );
    }


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
